#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.ext import webapp, db
from google.appengine.ext.webapp import util
from google.appengine.api import urlfetch
import urllib2
from datetime import datetime
from BeautifulSoup import BeautifulSoup
import time
import datetime



class Ammount(db.Model):
    ammt = db.IntegerProperty()
    pubdate = db.StringProperty()

class MainHandler(webapp.RequestHandler):
    def get(self):
        self.response.out.write('<h1>Cablegate Monitor</h1>')
        self.response.out.write('<p>The feed is located at <a href="/feed">http://cablegatemonitor.appspot.com/feed</a>, and notifies when new cables are released, only.')
        self.response.out.write('<p>In the next days a detailed feed will be provided, stay tuned.')
        self.response.out.write('<p><small>This tool is <strong>NOT</strong> affiliated to Wikileaks or any other organization or government or whatever.</small></p><img src="http://code.google.com/appengine/images/appengine-noborder-120x30.gif" />')

class FeedIt(webapp.RequestHandler):
    
    
    def store_ammount(self, ammount):
        buffer = Ammount()
        buffer.ammt = ammount
        buffer.pubdate = time.strftime("%a, %d %b %Y %H:%I:%S") 
        buffer.put()
    
    def get_stored_ammount(self):
        buffer = Ammount.all()
        ammt = None
        for chunk in buffer:
            ammt = chunk.ammt
        if ammt:
            return ammt
        else:
            return False
        
    def update_ammount(self, ammount):
        buffer = Ammount.all()
        for entry in buffer:
            entry.ammt = ammount
            entry.put()
        #print 'updated'
         
    def feed(self):
        ammount = Ammount.all()
        for entry in ammount:
            ammt = entry.ammt
            pubdate = entry.pubdate
        feed_opener = '<?xml version="1.0" ?><rss version="2.0"><channel><title>Cablegate Monitor</title><link>http://cablegate.wikileaks.org</link><description>Updates from Wikileaks Cablegate</description>'
        item = '<item><guid isPermaLink="false">%s</guid><pubDate>%s GMT</pubDate><title>New cables released. There are %s cables now.</title></item>' % (ammt,pubdate,str(ammt))
        feed_closer = '</channel></rss>'
        uia = feed_opener+item+feed_closer
        self.response.out.write(uia)
        
    def get(self):
        print ''
        self.response.headers['Content-Type'] = "text/xml; charset=utf-8"
        fetched = urlfetch.fetch("http://213.251.145.96/cablegate.html", payload=None, method='GET', headers={}, allow_truncated=False, follow_redirects=True, deadline=4)
        soup = BeautifulSoup(fetched.content)
        paragraph = str(soup.p)
        paragraph = paragraph[32:]

        new_ammount = int(paragraph[:3])
        old_ammount = self.get_stored_ammount()
       
        if not old_ammount:
            self.store_ammount(new_ammount)
        elif new_ammount > old_ammount:
            self.update_ammount(new_ammount)
        else:
            pass
        self.feed()
        

def main():
    application = webapp.WSGIApplication([('/', MainHandler),('/feed',FeedIt)],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
